import sqlite3
import os,sys
import pathlib
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import random
import loger
import time
log = loger.Logger('zhaotcp.shzenon.cn',StreamLevel='debug',FileLevel='info').logger
# chrome.exe --remote-debugging-port=9222 --user-data-dir=D:\selenium_chrome

root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))
def init():
    chrome_options = Options()
    # chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    chrome_options.binary_location=r"D:\chrome-win64\chrome.exe"
    chrome_options.add_argument('--user-data-dir=D:/selenium_chrome')
    service=Service(str(root/"chromedriver.exe"))

    browser = webdriver.Chrome(service=service, options=chrome_options)
    # browser = webdriver.Chrome(options=chrome_options)
    # browser.maximize_window()
    browser.get("https://zhaotcp.shzenon.cn/login")
    browser.implicitly_wait(15)
    return browser
def msleep(a=2,b=5):
    time.sleep(random.random()*(b-a)+a)
def findElementByXpath(xpath):
    obj=None
    try:
        obj=browser.find_element(By.XPATH,xpath)
    except:
        log.debug(f"not find xpath: {xpath}")
        return False
    else:
        return obj
def tryclick(xpath):
    try:
        browser.find_element(By.XPATH,xpath).click()
    except:
        log.debug(f"点击失败:{xpath}")
        return False
    else:
        log.debug(f"点击成功:{xpath}")
        return True

def tjs(js):
    try:
        obj = browser.execute_script(js)
    except:
        log.debug(f"执行失败:{js}")
        return False
    else:
        log.debug(f"执行成功:{js}")
        return obj
def switch2url(url):
        handles=browser.window_handles
        for i in handles:
            browser.switch_to.window(i)
            log.debug(browser.current_url[0:len(url)])
            if(browser.current_url[0:len(url)]==url):
                return True
                break
        return False
userinfo = None
def login():
    global userinfo
    global browser
    db=sqlite3.connect(root/"zhaotcp.shzenon.cn.db")
    r=db.execute("SELECT * FROM list where status ISNULL LIMIT 1;")
    userinfo=r.fetchone()
    print(userinfo)
    if(userinfo == None):
        input("已完成")
        exit()
    db.execute(f"UPDATE `list` SET `status`='1' WHERE (`id`={userinfo[0]})")
    db.commit()
    db.close()
    browser.get("https://zhaotcp.shzenon.cn/login")
    in_=findElementByXpath("//*[@id='userAccount']")
    in_.send_keys(userinfo[1])
    ip_=findElementByXpath("//*[@id='userPassword']")
    ip_.send_keys("111111")
    msleep(1,2)
    tryclick("//*[@id='__next']/div/div[2]/div[1]/form/div[2]/button")
    msleep(1,2)
    tjs('document.getElementsByTagName("button")[1].click();')
    msleep(2,4)
def SelectOptions(ans):

    for i in ans:
        tp=0
        tjs(f"list_=document.getElementsByClassName('flex-1');")
        for n in i :
            tjs(f"list_[{tp}].children[{n}].click();")
            msleep(3,5)
            tp=tp+1
        tjs(f"document.getElementsByTagName('button')[0].click();")
        # tjs(f"document.getElementsByClassName('hoverBg')[{i}].click();")
        tjs(f"sub_=document.getElementsByClassName('cursor-pointer');")
        r_=tjs("return sub_.length;")
        tjs(f"sub_[sub_.length-1].click();")
    msleep(1,2)

def s(i):
    tjs(f"tr[{i+1}].getElementsByTagName('button')[0].click();")
    msleep()
    tjs("document.getElementsByTagName('button')[0].click();")
    msleep()
    if(i==0): #基本情况#
        ans=[[1,0,1,1,0,5,3,0]]
        if(userinfo[3]=="女"):ans[0][1]=1
        log.debug(ans)
        SelectOptions(ans)
    if(i==1): #自我情况（一）#
        ans=[ [0,0,0,0,0,0,0,2,0,0]
             ,[0,2,1,0,0,2,0,2,0,0]
             ,[0]
            ]
        log.debug(ans)
        SelectOptions(ans)
    if(i==2): #自我情况（二）#
        ans=[ [0,0,0,0,0,0,0,0,0,0]
             ,[0,0,0,0,0,0,0,0,0,0]
             ,[0,0,0,0,0,0,0,0,0,0]
             ,[0,0,0,0,0,0,0,0,0,0]
             ,[0,0]
            ]
        log.debug(ans)
        SelectOptions(ans)
    if(i==3): #自我情况（三）#
        ans=[
            [3,3,3,3,3,3]
        ]
        log.debug(ans)
        SelectOptions(ans)
    if(i==4): #自我情况（四）-2024
        ans=[
            [3,3,3,3,3]
        ]
        log.debug(ans)
        SelectOptions(ans)
    if(i==5): #自我情况（五）-2024
        ans=[
            [0,0,0,0,0,0,0,0]
        ]
        log.debug(ans)
        SelectOptions(ans)
    if(i==6): #校园情况（一）-2024
        ans=[
            [0,0,0,0,0,1,0]
        ]
        log.debug(ans)
        SelectOptions(ans)
    if(i==7): #校园情况（二）-2024
        ans=[
            [0,0,0,0,0,0]
        ]
        log.debug(ans)
        SelectOptions(ans)
    if(i==8): #校园情况（三）-2024
        ans=[
            [0,0,0,0,0,0,0]
        ]
        log.debug(ans)
        SelectOptions(ans)
    if(i==9): #校园情况（四）-2024
        ans=[ [0,0,0,0,0,0,0,0,0,0]
             ,[0,0,0]

            ]
        log.debug(ans)
        SelectOptions(ans)   
    if(i==10): #家庭情况（一）-2024
        ans=[
            [0,0,0,0,0,0,0]
        ]
        log.debug(ans)
        SelectOptions(ans) 
    if(i==11): #家庭情况（二）-2024
        ans=[ [0,2,0,0,2,0,3,0,0,1]
             ,[0,0,3,0,0,3,0,0,3,1]
             ,[0,4,4,4]
            ]
        log.debug(ans)
        SelectOptions(ans) 
    browser.get("https://zhaotcp.shzenon.cn/")
    msleep()
def step():
    for i in range(12):
        tjs("tr=document.getElementsByTagName('tr');")
        title_=tjs(f"return tr[{i+1}].getElementsByTagName('button')[0].textContent;")
        log.debug(title_)
        if(title_ == "重新测试") : continue
        if(title_ == "立即测试"): s(i)
        if(title_ == False):break
def logout():
    tjs('document.getElementsByClassName("ant-space-item")[0].click();')
    msleep(1,3)
    tjs('document.querySelector(".ant-dropdown-menu-title-content").click()')
    msleep(1,3)
db=sqlite3.connect(root/"zhaotcp.shzenon.cn.db")
if __name__ == "__main__" :
    browser=init()
    while(True):
        login()
        step()
        logout()